<?php
function Priv(&$socket, $data, $public_data, &$priv_modules, &$sys_modules){
	//stream_set_blocking($socket,true);
	echo date("[H:i:s] d-m-Y").": ".$data;
		
	flush();
	$ex = explode(' ', $data);
	$rawcmd = str_replace(chr(13), '', str_replace(chr(10), '', explode(':', $ex[3]))); //removes newlines and get the command
	//$oneword = explode('<br>', $rawcmd);
	$channel = $ex[2];
	
	$nicka = explode('@', $ex[0]);
	$nickb = explode('!', $nicka[0]);
	$nickc = explode(':', $nickb[0]);

	$host = $nicka[1];
	$nick = $nickc[1];
    
	//we gotta respond to the PING's with a PONG
	if($ex[0] == "PING"){
		fputs($socket, "PONG ".$ex[1]."\n");
	}else{
		$args = ""; 
		for ($i = 4; $i < count($ex); $i++) { 
			$args .= $ex[$i].' '; 
		}
		unset($rawcmd[0]);
		$msg = trim(implode(':',$rawcmd)." $args");
		
		$privmodstmp =  $priv_modules;
		for($i = 0; $i < sizeof($priv_modules); $i++){
			for($j = 0; $j < sizeof($priv_modules[$i]); $j++){
				unset($privsmodstmp[$i][$j][1]);
			}
		}
		
		$public_data = array($nick, $channel, $rawcmd[1], $msg, $args, $users, false, $privmodstmp);	
		echo "COMMAND:".$ex[1]."\n";
		//time to check what Jacqli will do
		if($ex[1] == "PRIVMSG"){
			for($i = sizeof($sys_modules)-1; $i >= 0; $i--){
				$sys_modules[$i][1]($socket, $public_data, $priv_modules, $sys_modules);
			}
			for($i = sizeof($priv_modules)-1; $i >= 0;  $i--){
				for($j = sizeof($priv_modules[$i])-1; $j >= 0; $j--){
					$function = $priv_modules[$i][$j][1];
					$tmpdata = $function($public_data);
					//if(is_array($tmpdata) && sizeof($tmpdata) > 7 && is_array($tmpdata[7])){
						$public_data = $tmpdata;
						$public_data[6] = html_entity_decode($public_data[6],ENT_QUOTES,"UTF-8");
						if($public_data[6] != false){
							echo "$public_data[6]\n";
							$currmsg = msg($socket, "$public_data[6]\n",$currmsg);
							$i = -1; $j = -1;
						}
					/*}else{
						echo "data array is broken, function $i-$j:$priv_modules[$i][$j][1]\n";
					}*/
				}
			}
		}else{
			
		}
	}
	return $public_data;
}

function msg(&$sock, $arg, $currmsg){
	fputs($sock, $arg);
	return ($currmsg+5);
}
?>